package com.msh.automatic.android.control.task

import android.util.Log
import com.msh.automatic.android.control.service.MqttService
import com.msh.automatic.android.control.service.MqttService.Companion
import com.msh.automatic.android.control.util.EventUtil
import com.msh.automatic.android.control.util.api.TaskApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

object TaskManager {
    // 等待中的任务
    var waitBaseTasks = Channel<AppTask>(Channel.UNLIMITED)
    // 正在处理的
    var currentBaseTask:AppTask? = null
    val TAG = "TASK"

    private var job: Job? = null
    private var jobActive: Boolean = true

    fun getTaskLogId():String?{
       var currentBaseTask: AppTask = this.currentBaseTask ?: return null
        return currentBaseTask.getId()
    }
    fun startTask(task: AppTask){
        Log.i(TAG,"start: ${task.getId()}")
        GlobalScope.launch {
            Log.i(TAG,"log wait_execute: ${task.getId()}")
            TaskApi.log(task.getId(),TaskLog.TaskLogStatus.wait_execute,"")
            waitBaseTasks.send(task)
        }
    }

    fun stop(){
        this.jobActive = false
        job?.let {
            it.cancel()
        }
    }
    fun start(){
        val that = this
        job = GlobalScope.launch {
            Log.d(TAG, "开始执行定时任务: ${System.currentTimeMillis()}")

            while (that.jobActive) {
                // ✅ 这里执行你的定时任务
                Log.d(TAG, "执行定时任务: ${System.currentTimeMillis()} ${that.currentBaseTask?.let { it.taskLog.id }}")
                if(that.currentBaseTask != null){
                    delay(30_000)  // 30秒
                    // 已经有任务了。
                    continue
                }
                val currentBaseTask = waitBaseTasks.receive()
                Log.i(TAG,"log execute: ${currentBaseTask.getId()}")
                TaskApi.log(currentBaseTask.getId(),TaskLog.TaskLogStatus.execute,"")
                try {
                    if(currentBaseTask.start()){
                        that.currentBaseTask = currentBaseTask
                    }else{
                        TaskApi.log(currentBaseTask.getId(),currentBaseTask.taskLog.status,currentBaseTask.taskLog.message)
                    }
                }catch (e:Exception){
                    Log.e(TAG,"log execute: ${currentBaseTask.getId()}",e)
                }
            }
        }
    }
}